import { type User } from "@prisma/client";
import { create } from "zustand";
import { persist } from "zustand/middleware";
import easyFetch from "../api/easyfetch";

interface Me {
  user: User;
}

interface Authed {
  me: Me;
  authed: true;
}

interface Unauthed {
  authed: false;
}

type MeState = {
  auth: Authed | Unauthed;
  loading: boolean;
  /**
   * @returns `true` if my info is loaded successfully, or else `false`
   */
  reloadMe: () => Promise<boolean>;
};

const useMeStore = create<MeState>()(
  persist(
    (set) => ({
      auth: { authed: false },
      loading: true,
      reloadMe: async (): Promise<boolean> => {
        set({ loading: true });
        const result = await easyFetch.get<User | null>("/api/me");
        if (result.ok) {
          const me = result.data;
          if (me) {
            set({ auth: { authed: true, me: { user: me } }, loading: false });
            return true;
          } else {
            set({ auth: { authed: false }, loading: false });
            return false;
          }
        } else {
          console.error("Load me failed", result.message);
          set({ auth: { authed: false }, loading: false });
          return false;
        }
      },
    }),
    { name: "me" },
  ),
);

export default useMeStore;
